// eslint-disable-next-line import/no-extraneous-dependencies
import { Request, Response } from 'express';
import { parse } from 'url';
import mockjs from 'mockjs';
import { AdminTableListItem, AdminTableListParams } from '@/pages/ums/admin/adminData';

// mock tableListDataSource
const genList = () => {
    const tableListDataSource: AdminTableListItem[] = mockjs.mock({
        'list|100': [{
            adminId: /\d{5,10}/,
            adminName: '@word',
            password: '@word',
            phone: /1\d{10}/,
            email: '@email',
            openId: '@guid',
            nickName: '@name',
            realName: '@name',
            avatar: '@image("200x200", "#50B347", "#FFF", "M")',
            country: '@word',
            gender: '@integer(0,2)',
            province: '@word',
            city: '@word',
            remark: '@title',
            status: '@integer(0,1)',
            userType: '@integer(0,1)',
            'roles|2': [{
                    roleId: /\d{5,10}/,
                    roleName: '@word',
                }
            ],
            loginTime: '@datetime',
            parentId: /\d{5,10}/,
            deleteStatus: '@integer(0,1000)',
            createTime: '@datetime',
            creator: '@word',
            updateTime: '@datetime',
            modifier: '@word',
        }],
    }).list;
    return tableListDataSource;
};

let tableListDataSource = genList();

/**
 * 查询列表管理员
 */
function queryAdmin(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { current = 1, pageSize = 10 } = req.query;
    const params = (parse(realUrl, true).query as unknown) as AdminTableListParams;

    let dataSource = [...tableListDataSource].slice(
        ((current as number) - 1) * (pageSize as number),
        (current as number) * (pageSize as number),
    );
    const sorter = JSON.parse(params.sorter as any);
    if (sorter) {
        dataSource = dataSource.sort((prev, next) => {
            let sortNumber = 0;
            Object.keys(sorter).forEach((key) => {
                if (sorter[key] === 'descend') {
                    if (prev[key] - next[key] > 0) {
                        sortNumber += -1;
                    } else {
                        sortNumber += 1;
                    }
                    return;
                }
                if (prev[key] - next[key] > 0) {
                    sortNumber += 1;
                } else {
                    sortNumber += -1;
                }
            });
            return sortNumber;
        });
    }
    if (params.filter) {
        const filter = JSON.parse(params.filter as any) as {
            [key: string]: string[];
        };
        if (Object.keys(filter).length > 0) {
            dataSource = dataSource.filter((item) => {
                return Object.keys(filter).some((key) => {
                    if (!filter[key]) {
                        return true;
                    }
                    if (filter[key].includes(`${item[key]}`)) {
                        return true;
                    }
                    return false;
                });
            });
        }
    }

    const result = {
        data: dataSource,
        total: tableListDataSource.length,
        success: true,
        pageSize,
        current: parseInt(`${params.currentPage}`, 10) || 1,
    };

    return res.json(result);
}

/**
 * 获取管理员
 */
function getAdmin(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    let data;
    if(id){
        data = tableListDataSource.find((item) => item.adminId && item.adminId.toString()===id.toString());
    }

    const result = {
        data,
        success: true,
    };

    return res.json(result);
}
/**
 * 获取管理员详情
 */
function getAdminDetail(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    let data;
    if(id){
        const tabData = tableListDataSource.find((item) => item.adminId && item.adminId.toString()===id.toString());
        data = {
            ...tabData,
            roles: [{
                roleId: '0',
                roleName: 'role0',
            }]
        }
    }

    const result = {
        data,
        success: true,
    };

    return res.json(result);
}

/**
 * 获取管理员
 */
function getAdminRoles(req: Request, res: Response, url: string) {
    let realUrl = url;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    let data;
    if(id){
        data = [{
            roleId: '1',
            roleName: 'admin',
        },
        {
            roleId: '2',
            roleName: 'role2',
        },]
    }

    const result = {
        data,
        success: true,
    };

    return res.json(result);
}

/**
 * 新增管理员
 */
function addAdmin(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const data = req.body as AdminTableListItem;
        data.adminId = mockjs.mock(/\d{5,10}/);

    if(data){
        tableListDataSource.splice(0,0,data);
    }

    const result = {
        success: true,
    };
    return res.json(result);
}

/**
 * 更新管理员
 */
function updateAdmin(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    const params = req.body as AdminTableListItem;
    if(id && params){
        const data: AdminTableListItem|undefined = tableListDataSource.find((item) => item.adminId && item.adminId.toString()===id.toString());
        if(data){
            Object.assign(
                data,
                params
            )
        }
    }

    const result = {
        success: true,
    };
    return res.json(result);

}

/**
 * 删除管理员
 */
function deleteAdmin(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    tableListDataSource = tableListDataSource.filter((item)=>item.adminId!==id);

    const result = {
        success: true,
    };

    return res.json(result);
}

/**
 * 批量删除管理员
 */
function batchDeleteAdmin(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { ids } = req.body;
    if(ids && ids.length){
        tableListDataSource = tableListDataSource.filter((item)=>
            item.adminId && ids.indexOf(item.adminId)===-1
        );
    }

    const result = {
        success: true,
    };

    return res.json(result);
}

/**
 * 设置角色
 */
function updateAdminRole(req: Request, res: Response){
    const result = {
        success: true,
    };

    return res.json(result);
}
/**
 * 设置角色
 */
function getAdminRolesSelectItems(req: Request, res: Response){
    const data = [{
            roleId: '1',
            roleName: 'role1',
            status: 1,
        },
        {
            roleId: '2',
            roleName: 'role2',
            status: 1,
        },
        {
            roleId: '3',
            roleName: 'role3',
            status: 0,
        },
        {
            roleId: '4',
            roleName: 'role4',
        },
    ]
    const result = {
        success: true,
        data,
    };

    return res.json(result);
}


export default {
    'GET /api/ums/admin': queryAdmin,
    'GET /api/ums/admin/:id': getAdmin,
    'GET /api/ums/adminDetail/:id': getAdminDetail,
    'GET /api/ums/admin/roles/:id': getAdminRoles,
    'POST /api/ums/admin': addAdmin,
    'PUT /api/ums/admin/:id': updateAdmin,
    'DELETE /api/ums/admin/:id': deleteAdmin,
    'DELETE /api/ums/admin': batchDeleteAdmin,
    'POST /api/ums/admin/roles/relation': updateAdminRole,
    'GET /api/ums/adminRoles/selectItems': getAdminRolesSelectItems,
};
